<?php

/**
 * @author Eureka
 */
class TinyBase
{

	protected static $_instance;

	public function __construct()
	{
		spl_autoload_register(array('TinyBase', 'autoload'));
	}

	public static function getInstance()
	{
		if (is_null(self::$_instance))
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public static function autoLoad($name)
	{
		$controllerFile = APPLICATION_PATH . '/controllers/' . $name . '.php';
		$modelFile = APPLICATION_PATH . '/models/' . $name . '.php';
		
		$tinyController = './system/controllers/' . $name . '.php';
		if (file_exists($controllerFile))
		{
			require_once($controllerFile);
		}
		else if (file_exists($modelFile))
		{
			require_once($modelFile);
		}
		else if (file_exists($tinyController))
		{
			require_once($tinyController);
		}
		else if (file_exists($name . '.php'))
		{
			require_once($name . '.php');
		}
	}

	public function dispatch($controller, $action = "")
	{
		if (empty($controller))
		{
			$this->forward('index');
		}

		$controller = ucfirst($controller);

		if (empty($action))
		{
			$action = lcfirst($controller);
		}

		$controllerClass = $controller . 'Controller';
		$class = new $controllerClass;
		$action = $action . 'Action';
		$class->$action();
		exit(0);
	}

	public function forward($controller, $action ='', $params='')
	{
		header("Location: ?c=$controller&a=$action&$params");
		exit(0);
	}

	function get($var)
	{
		$postValue = $this->post($var);
		return!empty($postValue) ? $postValue : (isset($_GET[$var]) ? $_GET[$var] : "");
	}

	function getInt($var)
	{
		return isset($_GET[$var]) ? intval($_GET[$var]) : 0;
	}

	function post($var)
	{
		return isset($_POST[$var]) ? $_POST[$var] : "";
	}

}

